<template>
	<page-meta :root-font-size="fontSize"></page-meta>
	<view>
		<!-- <h-page-meta></h-page-meta> -->
		<view class="flex flex-ac flex-jc mg-30"
			style="border-radius: 20rpx;padding: 30rpx;border: solid 1rpx #007AFF;color:#007AFF;margin-bottom: 0;"
			@click="chooseImage()" v-if="form.idCardType == '身份证'">
			<uni-icons type="camera" size="25" color="#007AFF"></uni-icons>
			<view class="fs-30" style="margin-left: 10rpx;">身份证拍照新增</view>
		</view>
		<view class="pd-30">
			<u-form :model="form" ref="uForm" label-width="auto" :rules="rules">
				<u-form-item label="姓名:">
					<u-input v-model="form.name" placeholder="请输入姓名" />
				</u-form-item>
				<u-form-item label="手机号:">
					<u-input v-model="form.phone" maxlength="11" placeholder="请输入手机号" />
				</u-form-item>
				<u-form-item label="证件类型:">
					<u-input v-model="form.idCardType" @click="idCardTypeShow = true" type="select" />
					<u-action-sheet :list="idCardTypeArr" v-model="idCardTypeShow"
						@click="idCardTypeActionSheetCallback"></u-action-sheet>
				</u-form-item>
			<!-- 	<u-form-item v-if="form.idCardType === '身份证'" label="证件号:" prop="idCard">
					<u-input v-model="form.idCard" />
				</u-form-item> -->
				<!-- <u-form-item v-if="form.idCardType !== '身份证'" label="证件号:">
					<u-input v-model="form.idCard" />
				</u-form-item> -->
				<u-form-item label="证件号:">
					<u-input v-model="form.idCard" />
				</u-form-item>
				<u-form-item label="乘车人类型:">
					<u-input v-model="form.type" @click="show = true" type="select" />
					<u-action-sheet :list="typeArr" v-model="show" @click="typeActionSheetCallback"></u-action-sheet>
				</u-form-item>
			</u-form>
		</view>
		<view class="flex flex-ac flex-bt mg-30 pd-30 bg-FF" style="margin-top: 20rpx;border-radius: 20rpx;">
			<view class="fs-30">
				隐私政策
				<text style="margin-left: 10rpx;color: #19A0FF;" @click="showNoticeContent">点击查隐私政策 </text>
			</view>
			<view class="checkbox" :class="isCheckNotice ? 'checkbox-activite' : ''"
				@click="isCheckNotice = !isCheckNotice">
				<u-icon name="checkmark" color="#FFF" size="32"></u-icon>
			</view>
		</view>
		<u-popup v-model="showNotice" mode="bottom" border-radius="14" height="600rpx">
			<view style="padding: 30rpx;font-size: 36rpx;">
				<u-parse :html="noticeContent"></u-parse>
			</view>
		</u-popup>
		<view class="flex flex-ac flex-jc bg-main pd-30 fs-34 bt-login" hover-class="u-hover-class" @click="submit()">确定
		</view>
	</view>
</template>

<script>
	var _self;
	var app = getApp().globalData;
	//	每日识别次数为200次
	const _TOKENURL = 'https://aip.baidubce.com/oauth/2.0/token'; //获取token的接口
	const _URL = 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard'; //证件识别接口
	const _APIKEY = 'qUq2DuaiXsc3aG7epGZHfeZ7'; //证件识别key
	const _SECRETKEY = '0DBAfdeqmz2sD8ktqpiDgysmRWNacQAU'; ////证件识别 secret key
	import {
		pathToBase64,
		base64ToPath
	} from '@/components/imageTool/gsq-image-tools/image-tools/index.js';
	export default {
		data() {
			return {
				rules: {
					idCard: [{
							required: true,
							message: '请输入身份证号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
								return _self.$u.test.idCard(value);
							},
							message: '身份证号码不正确',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change', 'blur'],
						}
					]
				},
				isCheckNotice: false,
				showNotice: false,
				noticeContent: '',
				form: {
					name: '',
					phone: '',
					idCard: '',
					idCardType: '身份证',
					type: '成人'
				},
				idCardNumber: '',
				typeArr: [{
						text: '成人'
					},
					// {
					// 	text: '半票儿童'
					// },
					// {
					// 	text: '免票儿童'
					// }
				],
				idCardTypeArr: [{
						text: '身份证(新版台胞证,新版外国人身份证)',
						textNotes: '身份证',
					}, {
						text: '外国人身份证(旧版)',
						textNotes: '身份证',
					},
					{
						text: '护照',
						textNotes: '护照',
					},
					{
						text: '港澳通行证',
						textNotes: '港澳通行证',
					},
					{
						text: '台湾居民往来大陆通行证',
						textNotes: '台湾居民往来大陆通行证',
					}
					// ,
					// {
					// 	text: '出生证'
					// },
					// {
					// 	text: '军官证'
					// },
					// {
					// 	text: '武警警官证'
					// },
					// {
					// 	text: '士兵证'
					// },
					// {
					// 	text: '军队职工证'
					// },
					// {
					// 	text: '残疾军人证'
					// }
				],
				switchVal: false,
				show: false,
				idCardTypeShow: false,
				isAdd: true, //是否是添加
				AID: '',
				tokenData: '',
				carryNum: 0,
				userInfo: [],
				fontSize: ''
			};
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			_self.$refs.uForm.setRules(_self.rules);
		},
		onLoad(option) {
			_self = this;
			//设置页面字体大小
			_self.fontSize = app.fontSize;
			if (typeof option.item != 'undefined') {
				var arr = JSON.parse(decodeURIComponent(option.item));
				_self.AID = arr.AID;
				_self.form.name = arr.Name;
				_self.form.phone = arr.PhoneNumber;
				_self.form.idCard = arr.IDCard;
				_self.form.idCardType = arr.IDCardType;
				_self.form.type = arr.Type;
				//是否是添加信息
				_self.isAdd = false;
			}
			_self.tokenData = uni.getStorageSync('tokenData') || '';
			uni.getStorage({
				key: 'userInfo',
				success: function(res) {
					console.log('用户信息', res.data);
					_self.userInfo = res.data;
				},
				fail: function() {
					uni.navigateTo({
						url: '../../pages/Login/Login'
					});
				}
			});
		},
		methods: {
			showNoticeContent: function() {
				_self.GetTicketInstructionsMemo();
			},
			//--------------------------------------加载购票须知--------------------------------------
			GetTicketInstructionsMemo: function() {
				uni.showLoading({
					title: '正在加载...'
				})
				uni.request({
					url: _self.$h.expressInterface.expressInterface.GetTicketInstructionsMemo.url,
					method: _self.$h.expressInterface.expressInterface.GetTicketInstructionsMemo.method,
					header: _self.$h.expressInterface.expressInterface.GetTicketInstructionsMemo.header,
					data: {
						appSystemCode: _self.$h.expressInterface.expressInterface.appSystemCode.appSystemCode,
					},
					success: (res) => {
						uni.hideLoading();
						// console.log('购票须知',res)
						if (res.data.Success) {
							_self.showNotice = true;
							_self.noticeContent = res.data.Data;
						} else {
							_self.showToast('加载失败，请稍后重试', 'warning');
						}
					},
					fail(res) {
						uni.hideLoading();
					}
				});
			},
			//------------------------------身份证识别开始----------------------------------------------
			/**
			 * 获取身份证识别接口token
			 */
			getToken: function() {
				var that = this;
				uni.request({
					url: _TOKENURL,
					method: 'GET',
					data: {
						grant_type: 'client_credentials',
						client_id: _APIKEY,
						client_secret: _SECRETKEY
					},
					success(res) {
						var data = res.data;
						that.carryNum++;
						that.$set(data, 'createTime', new Date().getTime());
						uni.setStorageSync('tokenData', data);
						that.tokenData = uni.getStorageSync('tokenData') || '';
						that.idcard();
					},
					fail(err) {
						uni.hideLoading();
						uni.showToast({
							title: '图片文件识别失败，请手动填写身份证信息',
							icon: 'none',
							duration: 2000,
							mask: true
						});
					}
				});
			},
			/**
			 * @param {Object} image 图片base64
			 * 身份证识别接口
			 */
			idcard: function(image) {
				var that = this;
				uni.showLoading({
					title: '正在识别，请稍后'
				});
				if (new Date().getTime() - that.tokenData.createTime >= that.tokenData.expires_in * 1000 || that
					.tokenData == '') {
					if (that.carryNum < 5) {
						that.getToken();
					} else {
						uni.hideLoading();
						uni.showToast({
							title: '图片文件识别失败，请手动填写身份证信息',
							icon: 'none',
							duration: 2000,
							mask: true
						});
					}
					return;
				}
				that.carryNum = 0;
				uni.request({
					url: _URL,
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						image: image,
						// url: 'https://baidu-ai.bj.bcebos.com/ocr/idcard.jpeg',
						id_card_side: 'front', //front-正面|back-背面
						access_token: that.tokenData.access_token
					},
					success(res) {
						var data = res.data;
						console.log(data);
						if (data.idcard_number_type == 1) {
							if (data.image_status == 'normal') {
								that.form.name = data.words_result['姓名'].words;
								that.form.idCard = data.words_result['公民身份号码'].words;
								// words_result['出生'].words
								//words_result['性别'].words
								that.form.idCardType = '身份证';
							} else {
								uni.showToast({
									title: '请上传身份证正面图片',
									icon: 'none',
									duration: 2000,
									mask: true
								});
							}
						} else {
							uni.showToast({
								title: '图片文件识别失败，请手动填写身份证信息',
								icon: 'none',
								duration: 2000,
								mask: true
							});
						}
					},
					fail(res) {
						uni.showToast({
							title: '图片文件识别失败，请手动填写身份证信息',
							icon: 'none',
							duration: 2000,
							mask: true
						});
					},
					complete() {
						uni.hideLoading();
					}
				});
			},
			/**
			 * 选择图片并转换为base64
			 */
			chooseImage: function() {
				var that = this;
				uni.chooseImage({
					count: 1,
					sizeType: 'compressed',
					success(res) {
						var path = res.tempFilePaths[0];
						pathToBase64(path)
							.then(base64 => {
								that.idcard(base64);
							})
							.catch(error => {
								uni.showToast({
									title: '图片文件识别失败，请手动填写身份证信息',
									icon: 'none',
									mask: true
								});
							});
					}
				});
			},
			//------------------------------身份证识别结束----------------------------------------------
			typeActionSheetCallback(index) {
				this.form.type = this.typeArr[index].text;
			},
			idCardTypeActionSheetCallback(index) {
				// this.form.idCardType = this.idCardTypeArr[index].text;
				this.form.idCardType = this.idCardTypeArr[index].textNotes;
			},
			submit() {
				if (!_self.isCheckNotice) {
					_self.$u.toast('请勾选隐私政策');
					return
				}
				if (_self.form.name == '') {
					_self.$u.toast('请输入姓名');
					return;
				}
				if (!_self.$h.verify.isPhone(_self.form.phone)) {
					_self.$u.toast('请正确的手机号');
					return;
				}
				if (_self.form.idCard == '') {
					_self.$u.toast('请输入证件号');
					return;
				}
				let regs = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; //身份证
				if (_self.form.idCardType == '护照') {
					regs =
						/(^[EeKkGgDdSsPpHh]\d{8}$)|(^(([Ee][a-fA-F])|([DdSsPp][Ee])|([Kk][Jj])|([Mm][Aa])|(1[45]))\d{7}$)/; //护照（包括香港和澳门）

				} else if (_self.form.idCardType == '港澳通行证') {
					//let regs = /^[HMhm]{1}([0-9]{10}|[0-9]{8})$/; //港澳通行证
					regs = /^[a-zA-Z0-9]{6,10}$/; //港澳通行证
					console.log(regs, regs.test(_self.form.idCard));
				} else if (_self.form.idCardType != '台湾通行证') {
					regs = /^\\d{8}|^[a-zA-Z0-9]{10}|^\\d{18}$/ //台湾通行证
					///^([0-9]{8}|[0-9]{10})$/
				} else if (_self.form.idCardType != '外国人身份证(旧版)') {
					regs = /^[A-Z]{3}[0-9]{12}$/
				}

				if (!regs.test(_self.form.idCard)) {
					_self.$u.toast('证件号格式错误，请重新确认！');
					return;
				}
				//如果证件不是身份证则拼接  证件类型+‘,’+证件号
				if (_self.form.idCardType != '身份证') {
					_self.idCardNumber = _self.form.idCardType + ',' + _self.form.idCard;
				} else {
					_self.idCardNumber = _self.form.idCard;
				}
				//添加乘客
				if (_self.isAdd) {

					_self.GetContactsAddByID();
					// _self.$refs.uForm.validate(valid => {
					// 	if (valid) {
					// 		//提交
					// 		console.log(123456);
					// 		_self.GetContactsAddByID();
					// 	} else {
					// 		console.log('验证失败');
					// 	}
					// });
				} else {
					//修改乘客信息
					_self.GetContactsUpdateByID();
				}
			},
			//------------------------------编辑成功------------------------------
			GetContactsUpdateByID() {
				uni.showLoading({
					title: '正在修改信息...'
				})

				uni.request({
					url: _self.$h.expressInterface.expressInterface.GetContactsUpdateByID.url,
					method: _self.$h.expressInterface.expressInterface.GetContactsUpdateByID.method,
					data: {
						IDCard: _self.idCardNumber,
						Name: _self.form.name,
						tel: _self.form.phone,
						type: _self.form.type,
						contactsId: _self.AID
					},
					success(res) {
						uni.hideLoading();
						if (res.data.Success) {
							_self.$u.toast('编辑成功');
							setTimeout(function() {
								uni.navigateBack();
							}, 1000);
						} else {
							_self.$u.toast(res.data.Message);
						}
					},
					fail() {
						uni.hideLoading();
						_self.$u.toast('网络异常');
					}
				});
			},
			//------------------------------添加乘客信息------------------------------
			GetContactsAddByID() {
				console.log(65465, _self.idCardNumber);
				uni.showLoading({
					title: '正在添加乘客信息...'
				})
				uni.request({
					url: _self.$h.expressInterface.expressInterface.GetContactsAddByID.url,
					method: _self.$h.expressInterface.expressInterface.GetContactsAddByID.method,
					data: {
						IDCard: _self.idCardNumber,
						Name: _self.form.name,
						tel: _self.form.phone,
						type: _self.form.type,
						userid: _self.userInfo.Id
					},
					success(res) {
						uni.hideLoading();
						console.log('111', res);
						if (res.data.Success) {
							uni.showModal({
								title: '添加成功！',
								confirmText: '继续添加',
								cancelText: '返回',
								success(res) {
									if (res.confirm) {
										_self.form.name = '';
										_self.form.phone = '';
										_self.form.idCard = '';
										_self.form.idCardType = '身份证';
										_self.form.type = '成人';
									}
									if (res.cancel) {
										uni.navigateBack();
									}
								}
							});
						} else {
							_self.$u.toast(res.data.Message);
						}
					},
					fail() {
						uni.hideLoading();
						_self.$u.toast('网络异常');
					}
				});
			}
		}
	};
</script>

<style>
	.bt-login {
		margin: 50rpx;
		margin-top: 50rpx;
		border-radius: 50rpx;
		color: #fff;
		letter-spacing: 4rpx;
		box-shadow: 0px 7px 38px 8px rgba(235, 6, 70, 0.15);
	}

	.checkbox-activite {
		background: linear-gradient(270deg, #ef7d4e, #ec5249);
		border-color: #ec5249;
	}

	.checkbox {
		width: 50rpx;
		height: 50rpx;
		border: solid 1rpx #999;
		border-radius: 100%;
		text-align: center;
		line-height: 45rpx;
	}
</style>